package cobots.swarm.view;

import java.awt.event.MouseEvent;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.util.Vector;

import cobots.swarm.agents.LeaderAgent;
import cobots.swarm.agents.Target;
import cobots.swarm.main.OperatorAction;
import cobots.swarm.main.SwarmState;
import cobots.swarm.props.PropertiesClass;


public class MouseHandler {

	protected float iRadius = PropertiesClass.getIradius();
	protected float attractionRadius = iRadius;
	protected boolean growing = false;
	protected long clickTime = 0;
	protected short repulsionRadius = (short) PropertiesClass.getRepulsionRadius();
	protected short selectedLeader = -1, selectedTarget = -1;
	protected Point2D mousePressedPoint = null;	
	protected Vector<Point2D> path = new Vector<Point2D>();

	public void mouseClicked(Point2D worldLocation, int button, boolean controlDown) { 
		
		System.out.println("click");
		synchronized (SwarmState.leaders) {
			if (button == MouseEvent.BUTTON3 && !controlDown)
				selectedTarget = selectedLeader = -1;
			else if (selectedLeader == -1) {  //Here we select the leader 
				Point2D pt = new Point2D.Double();
				pt.setLocation(worldLocation);
				double minDist = Double.MAX_VALUE;				
				for (Short s : SwarmState.getFreeLeaderIds()) {
					LeaderAgent l = SwarmState.leader(s);
					if (l == null)
						return;
					if (l.distance(pt) < minDist) {
						minDist = l.distance(pt);
						selectedLeader = l.getId();		
						System.out.println("selected leader: "+selectedLeader);
						growing = true;
						clickTime = System.currentTimeMillis();
						attractionRadius = iRadius;
					}
				}

			}
			else if (controlDown && button == MouseEvent.BUTTON3) {
				SwarmState.clearPath(selectedLeader);
			}
			else if (controlDown && button == MouseEvent.BUTTON1) {
				if (new Rectangle2D.Double(-SwarmState.width/2, -SwarmState.height/2, SwarmState.width, SwarmState.height).contains(worldLocation))
					SwarmState.addToPath(selectedLeader, worldLocation);
			}
			else if (selectedTarget == -1){
				Point2D pt = new Point2D.Double();
				pt.setLocation(worldLocation);
				double minDist = Double.MAX_VALUE;
				for (Target t : SwarmState.targets.values()) {
					if (t.distance(pt) < minDist) {
						minDist = t.distance(pt);
						selectedTarget = t.getId();
					}
				}
				if (selectedTarget != -1) {
					SwarmState.getInteraction().addAction(new OperatorAction(selectedLeader, selectedTarget, attractionRadius));
					selectedTarget = selectedLeader = -1;
				}			
			}
		}
	}
}
